<template>
  <div class="p-4">
    <h2 class="text-xl font-bold mb-6">工厂管理系统</h2>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <el-card class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">今日考勤</span>
            <div class="flex items-center gap-2">
              <el-tag type="primary">今日出勤: {{ todayAttendanceCount }}人</el-tag>
              </div>
          </div>
        </template>
        <div class="space-y-3">
          <div v-if="attendanceUsers.length > 0" class="mt-4">
            <el-table :data="attendanceUsers" style="width: 100%" size="small" max-height="300">
              <el-table-column prop="username" label="姓名" width="80" />
              <el-table-column label="考勤类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getTagType(row.records[0]?.type)" size="small">
                    {{ getAttendanceTypeName(row.records[0]?.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="totalHours" label="工时" width="70">
                <template #default="{ row }">
                  {{ row.totalHours }}h
                </template>
              </el-table-column>
              <el-table-column prop="records[0].remark" label="备注" />
            </el-table>
          </div>
          <el-empty v-else description="暂无考勤数据" :image-size="50"></el-empty>
        </div>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">近期工作记录</span>
            <div class="flex items-center gap-2">
              <el-tag type="success">{{ recentWorkRecords.length }}条</el-tag>
              <el-tag type="warning">总金额: ¥{{ totalAmount }}</el-tag>
            </div>
          </div>
        </template>
        <el-table :data="recentWorkRecords" style="width: 100%" size="small">
          <el-table-column prop="username" label="姓名" width="80" />
          <el-table-column prop="workItemName" label="工件" />
          <el-table-column prop="quantity" label="数量" width="70">
            <template #default="{ row }">
              {{ row.quantity || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="金额" width="90">
            <template #default="{ row }">
              ¥{{ row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="时间" width="100">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">待审核记录</span>
            <el-tag type="warning">{{ pendingRecords.length }}条</el-tag>
          </div>
        </template>
        <el-table :data="pendingRecords" style="width: 100%" size="small">
          <el-table-column prop="username" label="姓名" width="80" />
          <el-table-column prop="name" label="工作内容" />
          <el-table-column prop="price" label="金额" width="80">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleAudit(row, 1)">通过</el-button>
              <el-button link type="danger" @click="handleAudit(row, 2)">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">出货情况</span>
            <el-tag type="info">{{ inStockProducts.total || 0 }}件待出库</el-tag>
          </div>
        </template>
        <el-table :data="inStockProducts.records || []" style="width: 100%" size="small">
          <el-table-column prop="workName" label="产品名称" />
          <el-table-column prop="workerName" label="生产人员" width="90" />
          <el-table-column prop="quantity" label="数量" width="70" />
          <el-table-column prop="createTime" label="生产时间" width="100">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleShip(row)">出库</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-dialog v-model="shipDialogVisible" title="产品出库" width="90%" :close-on-click-modal="false">
      <el-form :model="shipForm" label-width="80px">
        <el-form-item label="产品名称">
          <span>{{ currentProduct?.workName }}</span>
        </el-form-item>
        <el-form-item label="生产人员">
          <span>{{ currentProduct?.workerName }}</span>
        </el-form-item>
        <el-form-item label="客户信息" required>
          <el-input v-model="shipForm.customer" placeholder="请输入客户信息" />
        </el-form-item>
        <el-form-item label="出库数量" required>
          <el-input-number
            v-model="shipForm.quantity"
            :min="1"
            :max="currentProduct?.quantity || 1"
            :precision="0"
          />
          <span class="text-gray-500 ml-2">
            可出库数量: {{ currentProduct?.quantity || 0 }}
          </span>
        </el-form-item>
        <el-form-item label="出库时间" required>
          <el-date-picker
            v-model="shipForm.shippingTime"
            type="datetime"
            placeholder="选择出库时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 8, 0, 0)"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="shipForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="shipping" @click="confirmShip">确认出库</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="auditDialogVisible" :title="auditStatus === 1 ? '通过审核' : '驳回审核'" width="90%" :close-on-click-modal="false">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核备注">
          <el-input v-model="auditForm.remark" type="textarea" placeholder="请输入审核备注" />
        </el-form-item>
        <el-form-item v-if="auditStatus === 1" label="修改金额">
          <el-input-number v-model="auditForm.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="auditing" @click="confirmAudit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllAttendances } from '../api/attendance'
import { getSalaryStat } from '../api/salary'
import { getPendingRecords, auditWorkRecord } from '../api/workRecord'
import { getInStockProducts, shipProduct } from '../api/shipping'

// 数据
const todayAttendanceCount = ref(0)
const attendanceTypes = ref({})
const recentWorkRecords = ref([])
const totalAmount = ref(0)
const pendingRecords = ref([])
const inStockProducts = ref({ total: 0, records: [] })

// 出库相关
const shipDialogVisible = ref(false)
const shipping = ref(false)
const currentProduct = ref(null)
const shipForm = ref({
  customer: '',
  quantity: 1,
  shippingTime: '',
  remark: ''
})

// 审核相关
const auditDialogVisible = ref(false)
const auditing = ref(false)
const currentRecord = ref(null)
const auditStatus = ref(1)
const auditForm = ref({
  remark: '',
  price: 0,
  status: 1
})

// 考勤人员数据
const attendanceUsers = ref([])

// 获取标签类型
const getTagType = (type) => {
  const types = {
    1: 'success',  // 全天班
    2: 'warning',  // 半天班
    3: 'info'      // 小时班
  }
  return types[type] || ''
}

// 考勤类型名称映射
const getAttendanceTypeName = (type) => {
  const types = {
    1: '全天班(8小时)',
    2: '半天班(4小时)',
    3: '小时班'
  }
  return types[type] || '未知类型'
}

// 格式化日期显示
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const pad = (num) => String(num).padStart(2, '0')
  return `${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

// 获取今日考勤数据
const fetchTodayAttendance = async () => {
  try {
    // 格式化今天的日期为YYYY-MM-DD 格式
    const today = new Date()
    const formatDate = (date) => {
      const pad = (num) => String(num).padStart(2, '0')
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
    }
    const date = formatDate(today)
    
    console.log('获取考勤数据，日期:', date)
    const res = await getAllAttendances({ date })
    
    if (res.code === 200 && res.data) {
      // 处理考勤数据
      const typeCount = {}
      let total = 0
      
      // 保存有效的考勤用户数据
      attendanceUsers.value = res.data.filter(user => 
        user.records && user.records.length > 0
      ).sort((a, b) => {
        // 按考勤类型和姓名排序
        const typeA = a.records[0]?.type || 0
        const typeB = b.records[0]?.type || 0
        if (typeA !== typeB) return typeA - typeB
        return a.username.localeCompare(b.username)
      })
      
      // 统计各类型人数
      attendanceUsers.value.forEach(user => {
        const record = user.records[0]
        if (record && record.type) {
          typeCount[record.type] = (typeCount[record.type] || 0) + 1
          total++
        }
      })
      
      todayAttendanceCount.value = total
      attendanceTypes.value = typeCount
      console.log('考勤数据统计:', { 
        total, 
        typeCount,
        users: attendanceUsers.value
      })
    } else {
      console.warn('考勤数据格式异常:', res)
      todayAttendanceCount.value = 0
      attendanceTypes.value = {}
      attendanceUsers.value = []
    }
  } catch (error) {
    console.error('获取今日考勤数据失败:', error)
    todayAttendanceCount.value = 0
    attendanceTypes.value = {}
    attendanceUsers.value = []
  }
}

// 获取近期工作记录
const fetchRecentWorkRecords = async () => {
  try {
    const now = new Date()
    // 格式化时间为YYYY-MM-DD HH:MM:SS 格式
    const formatDateTime = (date) => {
      const pad = (num) => String(num).padStart(2, '0')
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
    }
    
    const endTime = formatDateTime(now)
    // 获取两天前的同一时间
    const startDate = new Date(now)
    startDate.setDate(startDate.getDate() - 2)
    const startTime = formatDateTime(startDate)
    
    console.log('查询时间范围:', { startTime, endTime })
    const res = await getSalaryStat({ startTime, endTime })
    
    if (res.code === 200 && res.data) {
      recentWorkRecords.value = res.data.workRecords || []
      totalAmount.value = res.data.totalAmount || 0
      console.log('工资统计数据:', res.data)
    } else {
      console.warn('工资统计数据格式异常:', res)
      recentWorkRecords.value = []
      totalAmount.value = 0
    }
  } catch (error) {
    console.error('获取工资统计数据失败:', error)
    recentWorkRecords.value = []
    totalAmount.value = 0
  }
}

// 获取待审核记录
const fetchPendingRecords = async () => {
  try {
    const res = await getPendingRecords()
    pendingRecords.value = res.data || []
  } catch (error) {
    console.error('获取待审核记录失败:', error)
  }
}

// 获取待出库产品
const fetchInStockProducts = async () => {
  try {
    const res = await getInStockProducts()
    if (res.code === 200 && res.data) {
      inStockProducts.value = res.data
      console.log('待出库产品:', res.data)
    } else {
      console.warn('获取待出库产品异常:', res)
      inStockProducts.value = { total: 0, records: [] }
    }
  } catch (error) {
    console.error('获取待出库产品失败:', error)
    inStockProducts.value = { total: 0, records: [] }
  }
}

// 处理出库
const handleShip = (product) => {
  currentProduct.value = product
  // 设置默认出库时间为当前时间
  const now = new Date()
  const formatDateTime = (date) => {
    const pad = (num) => String(num).padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
  }
  
  shipForm.value = {
    customer: '',
    quantity: 1,
    shippingTime: formatDateTime(now),
    remark: ''
  }
  shipDialogVisible.value = true
}

// 确认出库
const confirmShip = async () => {
  if (!shipForm.value.customer) {
    ElMessage.warning('请输入客户信息')
    return
  }

  if (!shipForm.value.quantity || shipForm.value.quantity <= 0) {
    ElMessage.warning('请输入有效的出库数量')
    return
  }

  if (shipForm.value.quantity > (currentProduct.value?.quantity || 0)) {
    ElMessage.warning('出库数量不能超过可出库数量')
    return
  }

  if (!shipForm.value.shippingTime) {
    ElMessage.warning('请选择出库时间')
    return
  }

  try {
    shipping.value = true
    await shipProduct(currentProduct.value.id, {
      customer: shipForm.value.customer,
      quantity: shipForm.value.quantity,
      shippingTime: shipForm.value.shippingTime,
      remark: shipForm.value.remark || undefined
    })
    ElMessage.success('出库成功')
    shipDialogVisible.value = false
    // 刷新待出库产品列表
    await fetchInStockProducts()
  } catch (error) {
    console.error('出库失败:', error)
    ElMessage.error('出库失败，请重试')
  } finally {
    shipping.value = false
  }
}

// 处理审核
const handleAudit = (record, status) => {
  currentRecord.value = record
  auditStatus.value = status
  auditForm.value = {
    remark: '',
    price: record.price,
    status
  }
  auditDialogVisible.value = true
}

// 确认审核
const confirmAudit = async () => {
  try {
    auditing.value = true
    await auditWorkRecord(currentRecord.value.id, auditForm.value)
    ElMessage.success(auditStatus.value === 1 ? '审核通过' : '已驳回')
    auditDialogVisible.value = false
    fetchPendingRecords()
  } catch (error) {
    console.error('审核失败:', error)
  } finally {
    auditing.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchTodayAttendance()
  fetchRecentWorkRecords()
  fetchPendingRecords()
  fetchInStockProducts()
})
</script>

<style scoped>
.el-card {
  margin-bottom: 1rem;
}

.el-table {
  margin-top: 0.5rem;
}
</style>